<?php
namespace app\controller;

use app\BaseController;
use app\common\lib\PingHelper;
use app\common\lib\WOL;
use app\middleware\Check;
use think\App;
use app\common\lib\WakeOnLAN;
use app\common\lib\Tool;
use think\facade\Cache;
use think\facade\Cookie;
use think\response\Json;

class Index extends BaseController
{
    public array $devices;

    public static int $COOKIE_EXPIRE = 604800; //Cookie保存7天




    public function __construct(App $app)
    {
        parent::__construct($app);
        self::setDevices(config('devices'));
    }

    /**
     * 获取设备在线状态
     * @return array
     */
    public function devices(): array
    {
        $helper = new PingHelper();
        $devices = $this->getDevices();
        foreach ($devices as $k=>$v) {
            $host = $v['host'];
            $result = $helper->ping($host);
            if (!$result) {
                $devices[$k]['status'] = 0;
            }
        }
        return $devices;
    }

    public function index()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $index = $this->request->post('index', null);
            $action = $this->request->post('action');//动作
            if (empty($action)) {
                return msg(-1, '参数错误,请输入动作');
            }
            if (isset($index) && is_numeric($index)) {
                if (empty($device = self::getDevices()[$index])) {
                    return msg(-1, '设备不存在');
                }
                try {
                    if ($action == 'on') {
                        $broadcastAddress = getBroadcast($device['host'],$device['subnetMask']);
//                    WakeOnLAN::wakeUp($device['mac'], $broadcastAddress);
//                    return msg(1, '发送指令成功');
//                    $wol = new WOL($device['host'], $device['mac'], 9, $device['host']);
//                    $msg = $wol->wake_on_lan();
                        $msg = Tool::wakeupOnLan($device['mac'], $broadcastAddress);
//                        $msg = Tool::wakeOnLan($device['host'], $device['mac']);
                        if(empty($msg) || is_bool($msg)){
                            $msg = '开机指令发送成功!';
                        }
                        return msg(1, $msg);
                    } elseif ($action == 'off') {
                        if (Tool::shutdownOnLan($device['host'], $device['shutdownPort'])) {
                            return msg(1, '关机指令发送成功!');
                        }
                        return msg(-1, '关机指令发送失败,请确保被控主机是否运行了关机服务(也有可能关机成功了，稍后再看看)');
                    }
                } catch (\Exception $e) {
                    return msg(-1, $e->getMessage());
                }
            }
            return msg(-1, '参数错误');
        }
        return view('index', ['devices' => self::devices()]);
    }


    /**
     * @return array
     */
    public function getDevices(): array
    {
        return $this->devices;
    }

    /**
     * @param array $devices
     */
    public function setDevices(array $devices): void
    {
        $this->devices = $devices;
    }

    public function login()
    {
        if ($this->isLogin) {
            header("Location:/");exit;
        }
        if ($this->request->isPost() && $this->request->isAjax()) {
            $password = $this->request->post('password');
            $remember = $this->request->post('remember');
            if ($password != config('app.password')) {
                return msg(-1, '密码错误');
            }
            if (!empty($remember) && $remember == '1') {
                $cacheKey = md5(uniqid(date('Y-m-d')));
                Cookie::set(Check::COOKIE_KEY, $cacheKey, self::$COOKIE_EXPIRE);
                Cache::set($cacheKey, 1, self::$COOKIE_EXPIRE);
            }else{
                session(Check::SESSION_KEY, true);
            }
            return msg(1, '成功', '/');
        }
        return \view('login');
    }

    public function getLanDevices(): Json
    {
        $devices = self::devices();
        return msg(1, '成功', $devices);
    }

}
